<template>
    <div class="main">
      <div class="bread" style="height: 50px; background: #77ddff; position: relative;">
        <!-- 面包屑导航部分 -->
        <el-breadcrumb separator="/">
          <el-breadcrumb-item style="font-weight: bold">管理界面</el-breadcrumb-item>
          <el-breadcrumb-item style="font-weight: bold">视频管理</el-breadcrumb-item>
          <el-breadcrumb-item style="font-weight: bold">添加视频</el-breadcrumb-item>
        </el-breadcrumb>
        <el-button type="success" @click="UploadDialogVisible = true" style="margin-left: 800px">添加视频</el-button>
      </div>
      <!-- 添加视频的窗口 -->
      <el-dialog :visible.sync="UploadDialogVisible" style="margin-top: -100px; height: 800px; margin-left: 100px" width="80%">
        <div style="height: 600px">
          <div class="form-grid-container">
            <el-form :model="form" label-width="120px" ref="form" :rules="rules" @submit.native.prevent>
              <el-form-item label="类型" prop="type" required>
                <el-select v-model="form.type" @change="handleTypeChange">
                  <el-option v-for="(option, index) in typeOptions" :key="index" :label="option" :value="option"></el-option>
                  <el-option :label="newTypeLabel" :value="newTypeValue" v-if="showNewTypeOption">添加新类型</el-option>
                </el-select>
                <el-input v-if="isAddingNewType" v-model="newTypeInput" placeholder="请输入新类型名称"></el-input>
              </el-form-item>
              <el-form-item label="视频" prop="video" required>
                <el-upload class="avatar-uploader" action="http://localhost:8080/video/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                  <video v-if="videoUrl" :src="this.videoUrl" style="width: 200px;height: 100px"></video>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="视频标题" prop="name" required>
                <el-input type="textarea" :rows="3.8" v-model="form.name" :placeholder="namePlaceholder"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm">发布</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-dialog>
      <!-- 视频列表 -->
      <el-table :data="videoList" style="width: 100%">
        <el-table-column prop="id" label="视频ID" width="100px"></el-table-column>
        <el-table-column prop="type" label="视频类型" width="200px">
          <template slot-scope="scope">
            <span>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="video" label="视频">
          <template slot-scope="scope">
            <video :src="scope.row.video" controls style="width: 240px; height: 240px"></video>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="视频标题"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" @click.native.prevent="confirmDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </template>

  <script>
  import axios from "axios";
  import { MessageBox } from "element-ui";

  export default {
    data() {
      return {
        UploadDialogVisible: false,
        form: {
          type: 0,
          video: "",
          name: "",
        },
        videoUrl: "",
        videoList: [],
        typeDetails: {},
        typeOptions: [],
        newTypeLabel: "添加新类型",
        newTypeValue: "new_type",
        showNewTypeOption: true,
        isAddingNewType: false,
        newTypeInput: "",
        namePlaceholder: "请输入视频标题",
        rules: {
          type: [{ required: true, message: "请选择视频类型", trigger: "blur" }],
          name: [{ required: true, message: "请输入视频标题", trigger: "blur" }],
        },
      };
    },
    methods: {
      fetchVideoList() {
        axios
         .get("http://localhost:8080/video/all-videos")
         .then((response) => {
            let videoList = response.data.data;
            // 对每个视频对象进行处理
            videoList.forEach((video) => {
              // 发起请求获取类型名称
              axios
               .get(`http://localhost:8080/video/type/${video.type}`)
               .then((Response) => {
                  video.type += ` (${Response.data.data})`;
                })
               .catch((error) => {
                  console.error("获取视频类型名称失败:", error);
                });
            });
            this.videoList = videoList;
          })
         .catch((error) => {
            console.error("获取视频列表失败:", error);
          });
      },
      deleteVideo(id) {
        axios
         .post(`http://localhost:8080/video/delete-video/${id}`)
         .then(() => {
            this.fetchVideoList();
          })
         .catch((error) => {
            console.error("删除视频失败:", error);
          });
      },
      confirmDelete(id) {
        MessageBox.confirm("确定要删除此视频吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
         .then(() => {
            this.deleteVideo(id);
          })
         .catch(() => {
            console.log("已取消删除操作");
          });
      },

      handleTypeChange() {
        if (this.form.type === "new_type") {
          // 新增类型，原有的类型数量加 1
          this.form.type = this.typeOptions.length + 1;
          this.isAddingNewType = true;
        } else {
          // 已有类型，位置加 1
          this.form.type = this.typeOptions.indexOf(this.form.type) + 1;
          this.isAddingNewType = false;
        }
      },

      fetchTypeOptions() {
        axios
         .get("http://localhost:8080/video/all-types")
         .then((response) => {
            this.typeOptions = response.data.data;
          })
         .catch((error) => {
            console.error("获取类型列表失败:", error);
          });
      },
      handleAvatarSuccess(response, file, fileList) {
        this.form.video = response.data;
        this.videoUrl = response.data;
      },
      beforeAvatarUpload(file) {
        const isLt20M = file.size / 1024 / 1024 < 20;
        if (!isLt20M) {
          this.$message.error("上传视频大小不能超过 20MB!");
          return false;
        }
        return true;
      },
      submitForm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.isAddingNewType) {
              // 如果是新增类型，发送请求添加新类型到服务器
              console.log("newTypeInput" + this.newTypeInput);
              axios
               .post("http://localhost:8080/video/add-type", null, {
                  params: {
                    sort: this.newTypeInput,
                  },
                })
               .then(() => {
                  console.log("新增类型添加成功");
                })
               .catch((error) => {
                  console.error("新增类型添加失败:", error);
                });
            }
            axios
             .post("http://localhost:8080/video/add-video", this.form)
             .then(() => {
                this.fetchVideoList();
                this.resetForm();
                this.UploadDialogVisible = false;
              })
             .catch((error) => {
                console.error("添加视频失败:", error);
              });
          } else {
            console.log("表单验证失败");
            return false;
          }
        });
      },
      resetForm() {
        this.$refs.form.resetFields();
        this.isAddingNewType = false;
        this.newTypeInput = "";
        this.form.video = "";
      },
    },
    mounted() {
      this.fetchVideoList();
      this.fetchTypeOptions();
    },
  };
  </script>

  <style scoped>
  .bread {
    height: 50px;
    display: flex;
    align-items: center;
  }
  .avatar-uploader.el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
   .avatar-uploader.el-upload:hover {
      border-color: #409EFF;
    }
  .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 240px;
      height: 240px;
      line-height: 240px;
      text-align: center;
    }
   .avatar {
      width: 120px;
      height: 120px;
      display: block;
    }
  </style>
